﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace GetGlobalIP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //UTF8Encoding utf8 = new UTF8Encoding();
            //WebClient webClient = new WebClient();
            //String externalIP = utf8.GetString(webClient.DownloadData("http://whatismyip.com/automation/n09230945.asp"));
            //tbIP.Text = externalIP;
            //tbIP.Text = CheckIp();
            tbIP.Lines = GetIps();
        }
        string CheckIp()
        {
            StreamReader reader;
            HttpWebRequest httpWebRequest;
            HttpWebResponse httpWebResponse;

            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://2ip.ru/");
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                reader = new StreamReader(httpWebResponse.GetResponseStream());
                //Regex r1 = new Regex("Имя вашего компьютера:*</td>");
                //Regex r2 = new Regex("Ваш IP адрес:*</big>");
                //string content = reader.ReadToEnd();
                //string host = r1.Match(content).Groups[0].Value;
                //string ip = r2.Match(content).Groups[0].Value;
                return System.Text.RegularExpressions.Regex.Match(reader.ReadToEnd(),
                    @"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})").Groups[1].Value;
                //return String.Format("{0}\n{1}", host, ip);
            }
            catch
            {
                return "error";
            }
        }
        string[] GetIps()
        {
            String host = System.Net.Dns.GetHostName();
            IPAddress[] ips = System.Net.Dns.GetHostAddresses(host);    
            string[] ret = new string[ips.Length];
            for(int i = 0;i<ips.Length;i++)
            {
                ret[i] = ips[i].ToString();
            }
            return ret;
        }
    }
}
